#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/wait.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <string.h>
#include <pthread.h>

#define BUF_SIZE 100
#define NAME_SIZE 20

void * send_msg(void* arg);
void * recv_msg(void* arg);
void error_handling(char * msg);

char msg[BUF_SIZE];
char name[NAME_SIZE] = "[DEFAULT]";

int main(int argc,char * argv[])
{
    int clnt_sock;
    struct sockaddr_in serv_addr;

    pthread_t send_thread,recv_thread;

    socklen_t addr_sz;
    int str_len,state;
    char buf[BUF_SIZE];
    void* thread_return; 

    if(argc !=4)
    {
        printf("Usage :%s  <IP> <port> <name>\n",argv[0]);
        exit(0);
    }

    sprintf(name,"[%s]",argv[3]);

    clnt_sock = socket(PF_INET,SOCK_STREAM,0);
    memset(&serv_addr,0,sizeof(serv_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons(atoi(argv[2]));

    // if(bind(serv_sock,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) ==-1)
    //     error_handling("bing error...");
    // printf("binding....\n");

    // if(listen(serv_sock,5) == -1)
    //     error_handling("listen error...");
    // printf("listening....\n");

    if(connect(clnt_sock,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1)
        error_handling("connect() error");
    
    pthread_create(&send_thread,NULL,send_msg,(void*)&clnt_sock);
    pthread_create(&recv_thread,NULL,recv_msg,(void*)&clnt_sock);

    pthread_join(send_thread,&thread_return);
    pthread_join(recv_thread,&thread_return);
    close(clnt_sock);
    return 0;
    
}



void * send_msg(void* arg)
{
    int clnt_sock = *((int *)arg);
    int str_len =0,i;
    char name_msg[BUF_SIZE+NAME_SIZE];
    while(1)
    {
        fgets(msg,BUF_SIZE,stdin);
        if(!strcmp(msg,"q\n") || !strcmp(msg,"Q\n"))
        {
            close(clnt_sock);
            exit(0);
        }
        sprintf(name_msg ,"%s %s",name,msg);
        write(clnt_sock,name_msg,strlen(name_msg));
    }
    return NULL;
}

void * recv_msg(void* arg)
{
    int clnt_sock = *((int *)arg);
    int str_len =0;
    char name_msg[BUF_SIZE+NAME_SIZE];
    while(1)
    {
        str_len = read(clnt_sock,name_msg,NAME_SIZE+BUF_SIZE-1);
        if(str_len == -1)
            return (void*) -1;
        name_msg[str_len] =0;
        fputs(name_msg,stdout);
    }
    return NULL;
}
void error_handling(char * message)
{
    printf("%s \n",message);
    exit(1);
}
